<template>
  <div class="create-record common-page">
    <!-- 顶部导航 -->
    <div class="header-nav">
      <div class="flex items-center gap-2">
        <el-icon class="cursor-pointer" @click="handleBack">
          <ArrowLeft />
        </el-icon>
        <span class="text-lg font-medium">创建档案</span>
      </div>
    </div>

    <!-- 步骤条 -->
    <div class="steps-container">
      <el-steps :active="currentStep" align-center>
        <el-step title="基本信息" />
        <el-step title="生活方式" />
        <el-step title="健康信息" />
      </el-steps>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <!-- 基本信息 -->
      <div v-show="currentStep === 0" class="step-content">
        <h3 class="step-title">基本信息</h3>
        <el-form
          :model="formData.basicInfo"
          label-width="100px"
          class="archive-form"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名" prop="name">
                <!-- <el-input
                  v-model="formData.basicInfo.name"
                  placeholder="请输入"
                  @blur="handleSearchUser"
                /> -->
                <el-select
                  v-model="formData.basicInfo.userId"
                  placeholder="请选择用户"
                  class="w-full"
                  filterable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.userId"
                    :label="user.userName || user.name"
                    :value="user.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="性别"
                prop="gender"
                :rules="[
                  { required: true, message: '请选择性别', trigger: 'change' }
                ]"
              >
                <el-select
                  v-model="formData.basicInfo.gender"
                  placeholder="请选择"
                  class="w-full"
                >
                  <el-option label="男" value="男" />
                  <el-option label="女" value="女" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="出生日期"
                prop="birthDate"
                :rules="[
                  {
                    required: true,
                    message: '请选择出生日期',
                    trigger: 'change'
                  }
                ]"
              >
                <el-date-picker
                  v-model="formData.basicInfo.birthDate"
                  type="date"
                  placeholder="请选择"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="民族">
                <el-select
                  v-model="formData.basicInfo.ethnicity"
                  placeholder="请选择民族"
                  class="w-full"
                  filterable
                >
                  <el-option
                    v-for="option in ETHNICITY_OPTIONS"
                    :key="option.value"
                    :label="option.text"
                    :value="option.text"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="本人电话"
                prop="phone"
                :rules="[
                  { required: true, message: '请输入电话号码', trigger: 'blur' }
                ]"
              >
                <el-input
                  v-model="formData.basicInfo.phone"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="身份证号"
                prop="idCard"
                :rules="[
                  { required: true, message: '请输入身份证号', trigger: 'blur' }
                ]"
              >
                <el-input
                  v-model="formData.basicInfo.idCard"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="联系人姓名">
                <el-input
                  v-model="formData.basicInfo.emergencyContactName"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人电话">
                <el-input
                  v-model="formData.basicInfo.emergencyContactPhone"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人地址">
                <el-input
                  v-model="formData.basicInfo.emergencyContactAddress"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="文化程度">
                <el-select
                  v-model="formData.basicInfo.education"
                  placeholder="请选择文化程度"
                  class="w-full"
                >
                  <el-option
                    v-for="option in EDUCATION_OPTIONS"
                    :key="option.value"
                    :label="option.text"
                    :value="option.text"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职业">
                <el-input
                  v-model="formData.basicInfo.occupation"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="婚姻状况">
                <el-select
                  v-model="formData.basicInfo.maritalStatus"
                  placeholder="请选择婚姻状况"
                  class="w-full"
                >
                  <el-option
                    v-for="option in MARITAL_STATUS_OPTIONS"
                    :key="option.value"
                    :label="option.text"
                    :value="option.text"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="医疗支付">
                <el-input
                  v-model="formData.basicInfo.medicalInsurance"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生活史">
                <el-input
                  v-model="formData.basicInfo.livingHistory"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作史">
                <el-input
                  v-model="formData.basicInfo.workHistory"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 生活方式 -->
      <div v-show="currentStep === 1" class="step-content">
        <h3 class="step-title">生活方式</h3>
        <el-form
          :model="formData.lifestyleInfo"
          label-width="100px"
          class="archive-form"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="吸烟情况">
                <el-input
                  v-model="formData.lifestyleInfo.smokingStatus"
                  placeholder="请输入吸烟情况"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="饮酒情况">
                <el-input
                  v-model="formData.lifestyleInfo.drinkingStatus"
                  placeholder="请输入饮酒情况"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="饮食习惯">
                <el-input
                  v-model="formData.lifestyleInfo.dietHabits"
                  placeholder="请输入饮食习惯"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="运动情况">
                <el-input
                  v-model="formData.lifestyleInfo.exerciseStatus"
                  placeholder="请输入运动情况"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 健康信息 -->
      <div v-show="currentStep === 2" class="step-content">
        <h3 class="step-title">健康信息</h3>
        <el-form
          :model="formData.healthInfo"
          label-width="100px"
          class="archive-form"
        >
          <div class="flex">
            <!-- 左侧内容 -->
            <div class="w-2/3 pr-4">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="现病史">
                    <el-input
                      v-model="formData.healthInfo.currentIllness"
                      placeholder="请输入现病史"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手术史">
                    <el-input
                      v-model="formData.healthInfo.surgeryHistory"
                      placeholder="请输入手术史"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="外伤史">
                    <el-input
                      v-model="formData.healthInfo.traumaHistory"
                      placeholder="请输入外伤史"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="家族病史">
                    <el-input
                      v-model="formData.healthInfo.familyHistory"
                      placeholder="请输入家族病史"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="过敏史">
                    <el-input
                      v-model="formData.healthInfo.allergyHistory"
                      placeholder="请输入过敏史"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="目前症状">
                    <el-input
                      v-model="formData.healthInfo.currentSymptoms"
                      placeholder="请输入目前症状"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 用药史表格 -->
              <div class="medication-history mt-4">
                <h4 class="text-lg font-medium mb-4">用药史</h4>
                <el-table :data="formData.healthInfo.medications" border>
                  <el-table-column prop="drugName" label="药品名称">
                    <template #default="{ row }">
                      <el-input
                        v-model="row.drugName"
                        placeholder="请输入药品名称"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="usageMethod" label="用法">
                    <template #default="{ row }">
                      <el-input
                        v-model="row.usageMethod"
                        placeholder="请输入用法"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="doseQuantity" label="单次剂量">
                    <template #default="{ row }">
                      <el-input
                        v-model="row.doseQuantity"
                        placeholder="请输入单次剂量"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="frequency" label="用药频次">
                    <template #default="{ row }">
                      <el-input
                        v-model="row.frequency"
                        placeholder="请输入用药频次"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="timing" label="用药时间">
                    <template #default="{ row }">
                      <el-input
                        v-model="row.timing"
                        placeholder="请输入用药时间"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="startDate"
                    label="用药开始日期"
                    width="150"
                  >
                    <template #default="{ row }">
                      <el-date-picker
                        v-model="row.startDate"
                        type="date"
                        placeholder="请选择用药开始日期"
                        class="w-full"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="treatment" label="疗程">
                    <template #default="{ row }">
                      <el-input
                        v-model="row.treatment"
                        placeholder="请输入疗程"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="notes" label="备注">
                    <template #default="{ row }">
                      <el-input v-model="row.notes" placeholder="请输入备注" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right">
                    <template #default="{ $index }">
                      <div
                        class="cursor-pointer text-gray-500 hover:text-red-500"
                        @click="handleDeleteMedication($index)"
                      >
                        <el-icon><Delete /></el-icon>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="mt-4">
                  <el-button @click="handleAddMedication">
                    + 添加用药记录
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 右侧内容 -->
            <div class="w-1/3 pl-4">
              <el-form-item label="既往病史">
                <el-input
                  v-model="formData.healthInfo.pastIllness"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入既往病史"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="footer-buttons">
      <div class="flex justify-between">
        <el-button v-if="currentStep > 0" @click="handlePrevStep"
          >上一步</el-button
        >
        <div v-else />
        <div class="flex gap-4">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            v-if="currentStep < 2"
            type="primary"
            @click="handleNextStep"
            >下一步</el-button
          >
          <el-button
            v-else
            type="primary"
            :loading="submitting"
            @click="handleSubmit"
            >创建档案</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { healthApi } from "@/api/health";
import { ArrowLeft, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getUserInfoByUserName } from "@/api/user";
import { userKey } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";
import {
  ETHNICITY_OPTIONS,
  EDUCATION_OPTIONS,
  MARITAL_STATUS_OPTIONS
} from "@/constants/common-const";
import { followApi } from "@/api/follow";

const router = useRouter();

// 当前步骤
const currentStep = ref(0);

// 提交状态
const submitting = ref(false);

// 表单数据
const formData = reactive({
  basicInfo: {
    userId: null,
    name: "",
    gender: "",
    birthDate: "",
    ethnicity: "",
    phone: "",
    idCard: "",
    emergencyContactName: "",
    emergencyContactPhone: "",
    emergencyContactAddress: "",
    education: "",
    occupation: "",
    maritalStatus: "",
    medicalInsurance: "",
    livingHistory: "",
    workHistory: ""
  },
  healthInfo: {
    currentIllness: "",
    pastIllness: "",
    familyHistory: "",
    currentSymptoms: "",
    allergyHistory: "",
    surgeryHistory: "",
    traumaHistory: "",
    medications: []
  },
  lifestyleInfo: {
    smokingStatus: "",
    dietHabits: "",
    drinkingStatus: "",
    exerciseStatus: ""
  }
});

// 返回上一页
const handleBack = () => {
  router.back();
};
// 用户列表数据
const userList = ref([]);

const currentUserId = computed(() => {
  return storageLocal().getItem(userKey).userId;
});
// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await followApi.getDoctorServiceUsers({
      userId: currentUserId.value
    });
    if (response.code === 0) {
      userList.value = response.data || [];
    } else {
      ElMessage.error("获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  }
};

// 取消创建
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要取消创建档案吗？已填写的信息将会丢失。",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "继续填写",
        type: "warning"
      }
    );
    router.back();
  } catch {
    // 用户取消
  }
};

// 上一步
const handlePrevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 下一步
const handleNextStep = () => {
  // 验证当前步骤的表单
  if (!validateCurrentStep()) {
    return;
  }

  if (currentStep.value < 2) {
    currentStep.value++;
  }
};

// 验证当前步骤
const validateCurrentStep = () => {
  switch (currentStep.value) {
    case 0: // 基本信息
      if (!formData.basicInfo.userId) {
        ElMessage.error("请选择用户");
        return false;
      }
      if (!formData.basicInfo.userId || formData.basicInfo.userId === 0) {
        ElMessage.error("请输入有效的用户姓名，系统未找到该用户信息");
        return false;
      }
      if (!formData.basicInfo.gender) {
        ElMessage.error("请选择性别");
        return false;
      }
      if (!formData.basicInfo.birthDate) {
        ElMessage.error("请选择出生日期");
        return false;
      }
      if (!formData.basicInfo.phone?.trim()) {
        ElMessage.error("请输入电话号码");
        return false;
      }
      if (!formData.basicInfo.idCard?.trim()) {
        ElMessage.error("请输入身份证号");
        return false;
      }
      break;
    case 1: // 生活方式
      // 生活方式信息为可选，不做强制验证
      break;
    case 2: // 健康信息
      // 健康信息为可选，不做强制验证
      break;
  }
  return true;
};

// 添加用药记录
const handleAddMedication = () => {
  formData.healthInfo.medications.push({
    dataType: 0,
    dataId: 0,
    drugName: "",
    usageMethod: "",
    doseQuantity: "",
    doseUnit: "",
    frequency: "",
    timing: "",
    startDate: "",
    treatment: "",
    notes: ""
  });
};

// 删除用药记录
const handleDeleteMedication = (index: number) => {
  formData.healthInfo.medications.splice(index, 1);
  ElMessage.success("删除成功");
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 最终验证
    if (!validateCurrentStep()) {
      return;
    }

    submitting.value = true;

    // 准备提交数据
    const submitData = {
      basicInfo: {
        ...formData.basicInfo,
        // 转换出生日期为时间戳
        birthDate: formData.basicInfo.birthDate
          ? new Date(formData.basicInfo.birthDate).getTime()
          : 0
      },
      healthInfo: formData.healthInfo,
      lifestyleInfo: formData.lifestyleInfo
    };
    console.log("submitData", submitData);
    // 调用创建档案接口
    const response = await healthApi.createHealthArchive(submitData);

    if (response.code === 0) {
      ElMessage.success("档案创建成功");
      // 跳转到档案列表或详情页
      router.push("/healthRecords/index");
    } else {
      ElMessage.error(response.message || "创建失败");
    }
  } catch (error) {
    console.error("创建档案失败:", error);
    ElMessage.error("创建失败，请稍后重试");
  } finally {
    submitting.value = false;
  }
};
// 组件挂载时获取用户列表
onMounted(() => {
  fetchUserList();
});
</script>

<style lang="scss" scoped>
.create-record {
  min-height: 100vh;
  // background: #f5f7fa;

  .header-nav {
    background: white;
    padding: 16px 24px;
    border-bottom: 1px solid #e4e7ed;

    .el-icon {
      font-size: 18px;
      color: #606266;

      &:hover {
        color: #409eff;
      }
    }
  }

  .steps-container {
    background: white;
    padding: 24px;
    margin: 16px 24px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .form-container {
    background: white;
    margin: 0 24px 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .step-content {
      padding: 24px;

      .step-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 24px;
        padding-bottom: 12px;
        border-bottom: 1px solid #e4e7ed;
      }
    }

    .archive-form {
      .el-form-item {
        margin-bottom: 18px;
      }

      :deep(.el-input),
      :deep(.el-select),
      :deep(.el-date-picker) {
        width: 100%;
      }
    }

    .medication-history {
      h4 {
        color: #303133;
      }

      :deep(.el-table) {
        .el-table__cell {
          padding: 8px;
        }
      }
    }
  }

  .footer-buttons {
    background: white;
    padding: 16px 24px;
    margin: 0 24px 24px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}
</style>
